//
//  QQZipViewController.swift
//  ZipTools
//
//  Created by 齐庆斌 on 2018/4/13.
//  Copyright © 2018年 齐庆斌. All rights reserved.
//

import UIKit
fileprivate let ZipCellID = "UnzipTabViewCell"

class QQZipViewController: UIViewController {
    
    // 获取文件夹下所有文件
    lazy var paths: [UnzipData] = {
        var zips = [UnzipData]()

        let paths: [String] = FileTool.getAllFilesFromTmp()
        
        for filePath in paths {
            let zip = UnzipData()
            zip.path = filePath
            zips.append(zip)
            print("path = \(filePath)")
        }
        
        return zips
    }()
    
    lazy var tbView: UITableView = {
        let tabView = UITableView()
        tabView.delegate = self
        tabView.dataSource = self
        tabView.separatorStyle = .none
        tabView.register((UINib(nibName: ZipCellID, bundle: nil)), forCellReuseIdentifier: ZipCellID)
        
        tabView.frame = self.view.frame
        
        
        return tabView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.title = "文件列表"
        self.view.addSubview(tbView)

        print("count = \(paths.count)")
    }
}

extension QQZipViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return paths.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ZipCellID) as! UnzipTabViewCell
        cell.delegate = self
        cell.filesPaths = (paths[indexPath.row], false)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 46.0
    }
}

extension QQZipViewController: ZipDelegate {
    func startUnzip(cell: UnzipTabViewCell) {
        FileTool.createDirectory(name: "your", isAutomicCreate: true)
        print("paths = \(FileTool.getTmp() + "/" + cell.filesPath.text!) ;  document = \(FileTool.getDocument())")
        if ZipTool.zipFiles(files: [FileTool.getTmp() + "/" + cell.filesPath.text!], path: FileTool.getDocument() + "/password.zip") {
            print("success")
        }else {
            print("failed")
        }
    }
    
    
}
